package com.gosuncn.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import org.bouncycastle.util.encoders.Base64;

import java.io.ByteArrayOutputStream;

/**
 * @Description: 生成二维码
 * @param:
 * @return:
*/
public class QRCodeUtil {

	/**
	 * @Description: 生成二维码
	 * @param:
	 * @return:
	*/
	public static byte[] getQRBytes(String text, int width, int height) {
		byte[] pngData = null;
		try {
	        QRCodeWriter qrCodeWriter = new QRCodeWriter();
	        //防止中文乱码
			text=new String(text.getBytes("UTF-8"),"ISO-8859-1");
	        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
	        ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
	        MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
	        pngData = pngOutputStream.toByteArray(); 
		} catch (Exception e) {
			e.printStackTrace();
		}
        return pngData;
	}
	
	public static String getQRBase64(String text, int width, int height) {
		byte[] QRBytes = getQRBytes(text, width, height);
		byte[] base64Bytes = Base64.encode(QRBytes);
		return new String(base64Bytes);
	}
	
	public static void main(String[] args) {
		System.out.println(getQRBase64("欢迎光临",200,200));
	}
	
	
}
